Repository navigation
Add polling mode and callback registration to EventDispatcher - #3715
yanglimingcn wants to merge 2 commits into
Conversation
There was a problem hiding this comment.
🔵 Needs a closer look
The cross-platform polling and callback-shutdown changes introduce complex concurrency and platform-specific behavior, while dependency-blocked builds and tests leave runtime and shutdown-race validation unverified.
No open issues 🎉
What changed in this PR
This pull request adds optional non-blocking epoll/kqueue polling and per-tag callback registration to EventDispatcher, while preserving existing bthread scheduling behavior. It also adds lifecycle, rollback, shutdown, and TCP processing tests.
Changes:
- Added configurable polling mode for epoll and kqueue backends.
- Added per-tag callback registration and synchronous unregistration with dispatcher-local contexts.
- Added rollback, stale-token protection, shutdown acknowledgement, and lifecycle test coverage.
- Review identified a moderate shutdown race: registration can report success after concurrent shutdown has already released the callback contexts. Registration and shutdown need a synchronization gate or rollback/recheck.
This pull request requires changes.
| File | Description |
|---|---|
test/brpc_event_dispatcher_unittest.cpp |
Adds coverage for polling, callback isolation and lifecycle, shutdown races, rollback, and TCP scheduling. |
src/brpc/event_dispatcher.h |
Defines polling configuration, callback APIs, registration tokens, dispatcher contexts, and lifecycle state. |
src/brpc/event_dispatcher.cpp |
Implements callback registration, command acknowledgement, rollback, shutdown handling, and global dispatcher initialization. |
src/brpc/event_dispatcher_kqueue.cpp |
Integrates polling mode and atomic lifecycle handling into the kqueue backend. |
src/brpc/event_dispatcher_epoll.cpp |
Integrates polling mode and atomic lifecycle handling into the epoll backend. |
Review effort: Lite
|
What's the user case of this feature? The Problem Summary in the description is empty, and the tree already has per-tag polling implementations with dedicated poller bthreads for URMA ( |
feaf099 to
7a73730
Compare
Updated |
There was a problem hiding this comment.
🔵 Needs a closer look
Cross-thread callback lifetimes and shutdown synchronization in platform-specific event loops cannot be validated because the reported build and tests are blocked by missing Protobuf and Google Test dependencies, requiring human runtime validation.
No open issues 🎉
Review effort: Lite
In latency-sensitive scenarios where advanced hardware features cannot be utilized, employing a polling mode for TCP can significantly reduce latency—especially when there is only one worker per tag—by substantially lowering the overhead associated with bthread scheduling. A similar implementation is also supported in the TCP mode of SPDK. |
| _polling_command.store(&command, std::memory_order_release); | ||
| } | ||
| // Only polling dispatchers accept commands, so no wakeup syscall is needed. | ||
| CHECK_EQ(0, command.done.wait()); |
There was a problem hiding this comment.
If the first dispatcher for the same tag starts successfully but the second fails to start because file descriptors are exhausted or bthread creation fails, this still publishes a command to the second dispatcher. Both its _stop and _polling_finished are false, but no thread can call done.signal(). Registration will wait indefinitely while holding the tag lock.
There was a problem hiding this comment.
Good catch. A dispatcher that fails to start never reaches FinishPolling(), so checking _stop and _polling_finished alone was not enough.
SetPollingCallbacks() now checks for a valid bthread ID before publishing the command. If the second dispatcher failed to start, registration rolls back the callbacks already installed on the first dispatcher and returns -1 with errno = ESHUTDOWN, without issuing a token. We also made Start() fail if the wakeup pipe cannot be created, so a partially initialized dispatcher cannot accept polling commands.
| registration->_tag = tag; | ||
| registration->_id = state->id; | ||
| group.state = std::move(state); | ||
| return 0; |
There was a problem hiding this comment.
After dispatcher 0 confirms initialization, it can complete Stop(), Join(), and release_fn before dispatcher 1 initializes. The two dispatchers have therefore never been ready at the same time, yet this still publishes a token and returns 0.
There was a problem hiding this comment.
This race is still possible. Registration waits for each dispatcher to acknowledge initialization, but an earlier dispatcher can stop and run release_fn while registration is still waiting for a later one. A successful return therefore means every dispatcher acknowledged installation, not that they were all ready at the same time. The token identifies the registration; it is not a liveness guarantee.
The startup-failure fix does not address this race. To guarantee that all dispatchers are still ready when the token is published, we would need to synchronize the final registration commit with Stop() and event-loop exit, and roll back if shutdown wins. Checking Running() one dispatcher at a time would not close the race.
| for (int i = 0; i < g_edisp_num; ++i) { | ||
| CHECK_EQ(0, dispatchers[i].SetPollingCallbacks(nullptr)); | ||
| } | ||
| group.state.reset(); |
There was a problem hiding this comment.
group.state.reset() destroys the callback's captured objects while holding group.mutex. If the deleter of the last shared_ptr unregisters the same tag again, the calling thread will deadlock before token validation. At this point, all dispatchers have already confirmed removal,
| // back all initialized contexts. Duplicate registration fails with EEXIST. | ||
| // Callbacks are serial per dispatcher, but concurrent across dispatchers. They | ||
| // must not block, throw, or synchronously register/unregister callbacks (EDEADLK). | ||
| // poll_fn must be non-null. Returns 0 on success, -1 with errno on failure. |
There was a problem hiding this comment.
Please clarify the earliest point at which poll_fn can run. Currently, dispatcher 0 can consume events from the external queue before dispatcher 1 fails to initialize and the overall registration returns -1. Callers need to know that events may already have been processed despite this failure so they can arrange enabling and retries correctly.
Add event_dispatcher_use_polling for non-blocking epoll/kqueue polling while preserving the bthread model and existing urgent/background scheduling switch. Support per-tag callback registration with dispatcher-local contexts, initialization rollback, and synchronous unregistration. Use atomic stop and task identifiers and safely acknowledge pending callback commands during shutdown. Add tests for idle polling, tag isolation, callback lifecycle, concurrent shutdown, and TCP urgent/background processing. Validation: git diff --check passed. Build and unit tests remain blocked by missing Protobuf dependencies and a Google Test download timeout.
7a73730 to
1d6ec2a
Compare
| CHECK_EQ(0, g_edisp[i * FLAGS_event_dispatcher_num + j].Start(&attr)); | ||
| attr.tag = (BTHREAD_TAG_DEFAULT + i) % g_edisp_ntags; | ||
| g_edisp[i * g_edisp_num + j].set_priority_index(j); | ||
| CHECK_EQ(0, g_edisp[i * g_edisp_num + j].Start(&attr)); |
There was a problem hiding this comment.
A pipe() failure now closes the event queues that were already created, but when crash_on_fatal_log=false, the CHECK_EQ here allows global initialization to complete. The fd hash can still select this member afterward, so ordinary TCP AddConsumer() calls will continue to return EINVAL even after the quota recovers.
| return -1; | ||
| } | ||
| std::unique_ptr<EventDispatcherPollingState> state( | ||
| new EventDispatcherPollingState(callbacks, ++group.next_id)); |
There was a problem hiding this comment.
EventDispatcherPollingState's callbacks(cb) invokes the user function object's copy constructor while holding group.mutex. If copying unregisters the same tag using an old token, it waits for the lock it already holds before validating the token, even if the token has expired.
| for (int i = 0; i < g_edisp_ntags * g_edisp_num; ++i) { | ||
| if (g_edisp[i].IsDispatcherThread()) { |
| int RegisterPollingCallbacksWithTag(bthread_tag_t tag, | ||
| const PollingCallbacks& callbacks, | ||
| PollingRegistration* registration); | ||
|
|
||
| // On success, all callbacks have stopped and release_fn has completed. This | ||
| // does not stop dispatchers or TCP traffic. Returns 0 or -1 with errno. | ||
| int UnregisterPollingCallbacks(PollingRegistration registration); |
Fail fast when a global dispatcher cannot start so fd routing never publishes an unusable shard. Copy polling callbacks outside the group lock and recheck registration before installation. Cover fd exhaustion and callback-copy reentrancy in regression tests.

Add event_dispatcher_use_polling for non-blocking epoll/kqueue polling while preserving the bthread model and existing urgent/background scheduling switch.
Support per-tag callback registration with dispatcher-local contexts, initialization rollback, and synchronous unregistration. Use atomic stop and task identifiers and safely acknowledge pending callback commands during shutdown.
Add tests for idle polling, tag isolation, callback lifecycle, concurrent shutdown, and TCP urgent/background processing.
Validation: git diff --check passed. Build and unit tests remain blocked by missing Protobuf dependencies and a Google Test download timeout.
What problem does this PR solve?
Issue Number: resolve
Problem Summary:
In latency-sensitive scenarios where advanced hardware features cannot be utilized, employing a polling mode for TCP can significantly reduce latency—especially when there is only one worker per tag—by substantially lowering the overhead associated with bthread scheduling. A similar implementation is also supported in the TCP mode of SPDK.
What is changed and the side effects?
Changed:
Side effects:
Performance effects:
Breaking backward compatibility:
Check List: